package com.laiyizhan.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
 * 签名工具
 * Created by folie
 */
public class SignUtils {

    private static final Logger log = LoggerFactory.getLogger(SignUtils.class);

    /**
     * 获取请求参数中的签名
     *
     * @param queryMap
     * @param app_secret
     * @return
     */
    public static String getSign(Map<String, String> queryMap, String app_secret) {
        if (queryMap != null && !queryMap.isEmpty()) {
            ArrayList<String> list = new ArrayList<String>();
            for (String key : queryMap.keySet()) {
                String value = queryMap.get(key);
                if ("sign".equals(key)) {
                    // sign 跳过
                    continue;
                }
                list.add(key + "=" + value + "&");
                log.debug("key={}, value={}", key, value);
            }

            int size = list.size();
            String[] arrayToSort = list.toArray(new String[size]);
            Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < size; i++) {
                sb.append(arrayToSort[i]);
            }
            String result = sb.toString();
            result += "app_secret=" + app_secret;
            log.info("签名前: {}", result);
            result = MD5.md5(result).toUpperCase();
            log.info("签名后: {}", result);
            return result;
        }
        return null;
    }
}
